﻿<html>
    <head>
        <meta charset='utf-8'>
        <title>猜数字</title>
        <script type="text/javascript">
            var TABLE_WIDTH = "150px";
            var ANSLEN = 4, CHANCES = 8;
            var answer, chance = 0;

            /*This function is a shorter form of document.getElementById("name")*/
            function __id(__obj)
            {
                if ("string" == typeof(__obj))
                {
                    return document.getElementById(__obj);
                }
                else
                {
                    return __obj;
                }
            }

            /*This function will be executed when the page was loaded*/
            function guessnum_init()
            {
                var i;

                //Initialize table
                var table = __id("table_results");
                table.width = TABLE_WIDTH;
                table.border = "0";
                for (i = 0; i < CHANCES; i++)
                {
                    table.insertRow(i);
                    table.rows[i].insertCell(0);
                    table.rows[i].insertCell(1);
                }

                //Reset game
                guessnum_reset();
            }
            /*This function will be executed when starting a new game*/
            function guessnum_reset()
            {
                var i, ans_digit;
                var table = __id("table_results");

                /* ---- Initialization of UI ---- */

                //Initialize textfields
                __id("ans_input").disabled=false;
                __id("ans_input").value = "";
                __id("btn_submit").disabled=false;

                for (i = 0; i < CHANCES; i++)
                {
                    table.rows[i].cells[0].innerHTML = "&nbsp;";
                    table.rows[i].cells[1].innerHTML = "&nbsp;";
                }

                //Init status area
                __id(game_result).innerHTML = "&nbsp;";

                /* ---- Initialization of Game ---- */

                chance = 0;

                //Generate answer
                answer = "";
                for (i = 0; i < ANSLEN; i++)
                {
                    do
                    {
                        ans_digit = String.fromCharCode(Math.random() * 10 + "0".charCodeAt(0));
                    }
                    while (-1 != answer.indexOf(ans_digit))
                    answer += ans_digit;
                }
            }

            /*Check if inputed answer is valid*/
            function ans_check(ans_src)
            {
                //Check length
                if (ANSLEN != ans_src.length)
                {
                    return false;
                }

                //Check if all the chars are digits
                //as well as detecting duplicated digits
                var i, digit_check;

                for (i = 0; i < ANSLEN; i++)
                {
                    digit_check = ans_src.charAt(i);

                    //Found non-digit character
                    if (-1 == digit_check.search("[0-9]"))
                    {
                        return false;
                    }
                    //Found duplicated digit
                    else if (ans_src.indexOf(digit_check)
                             != ans_src.lastIndexOf(digit_check))
                    {
                        return false;
                    }
                }

                return true;
            }

            /*Check the answer and return ?A?B*/
            function ans_result_A(ans_src)  //Both location and digit are right
            {
                var i, result = 0;

                for (i = 0; i < ANSLEN; i++)
                {
                    if (answer.charAt(i) == ans_src.charAt(i))
                    {
                        result++;
                    }
                }

                return result;
            }
            function ans_result_B(ans_src)  //Digit exists but misplaced
            {
                var i, result = 0;

                for (i = 0; i < ANSLEN; i++)
                {
                    if (-1 != answer.indexOf(ans_src.charAt(i))
                        && (answer.charAt(i) != ans_src.charAt(i)))
                    {
                        result++;
                    }
                }

                return result;
            }

            /*
            When "submit" was clicked or Enter key pressed, 
            this will be executed.
            */
            function ans_submit()
            {
                var ans = __id("ans_input").value;
                var resA, resB;

                __id("ans_input").value = "";

                //Check answer
                if (!ans_check(ans))
                {
                    window.alert("输入的不是有效答案，\n请重新输入。");
                    return;
                }

                resA = ans_result_A(ans);
                resB = ans_result_B(ans);

                //Update UI and show the result
                if ((ANSLEN == resA) && (0 == resB))    //Game win
                {
                    __id("table_results").rows[chance].cells[0].innerHTML
                        = "<font color=#FF0000>" + ans + "</font>";
                    __id("table_results").rows[chance].cells[1].innerHTML
                        = "<font color=#FF0000>" + resA + "A" +resB + "B" + "</font>";

                    __id("btn_submit").disabled = true;
                    __id("ans_input").disabled = true;
                    __id(game_result).innerHTML = "<font color=#FF0000>猜对了！！！</font>";
                    window.alert("恭喜你\n猜对了");
                }
                else
                {
                    __id("table_results").rows[chance].cells[0].innerHTML = ans;
                    __id("table_results").rows[chance].cells[1].innerHTML
                        = resA + "A" +resB + "B";

                    if (chance >= CHANCES - 1)   //game lose
                    {
                        __id("btn_submit").disabled = true;
                        __id("ans_input").disabled = true;
                        __id(game_result).innerHTML = "正确答案：" + answer;
                        window.alert("真可惜\n没猜对");
                    }
                    else
                    {
                        chance++;
                    }
                }
            }

            /*Dealing with key events*/
            function ans_submit_key(event)
            {
                if (13 == event.keyCode)
                {
                    ans_submit();
                }
            }
        </script>
    </head>
    <body onload="guessnum_init();">
        <h1>猜数字游戏</h1>
        <p>
            请输入数字：
            <input type="textfield" id="ans_input" size="4" maxlength="4" onkeypress="ans_submit_key(event);"/>
            <input type="button" value="提交" id="btn_submit" onclick="ans_submit();">
            <input type="button" value="重玩" id="btn_submit" onclick="guessnum_reset();">
        </p>
        <table id='table_results'></table>
        <p id='game_result'></p>

        <hr>

        <h2>游戏规则</h2>
        <p>
输入一个没有重复数字的四位数，然后按Enter键或点击“提交”，得出一个以?A?B形式给出的结果。其中A表示数字和位置均正确，B表示数字存在但位置错误。当猜到4A0B时为猜对，猜错8次则游戏结束并显示正确结果。点击“重玩”开始新游戏。
        </p>
        <!--PS：猜一次即猜对的几率为1/5040。猜到0A4B时有1/24的几率在下一次猜对。-->

        <hr>

        <p align='center'>
            作者：Frank<br/>
            2012-05-05
        </p>
    </body>
</html>
